package com.xframework.aop;

import com.xframework.Base;
import com.xframework.dao.DynamicDataSourceHandler;
import com.xframework.dao.DynamicDataSource;
import com.xframework.model.DynamicDataSourceNameList;
import org.aspectj.lang.JoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * 切换数据源(不同方法调用不同数据源)
 */
public class DynamicDataSourceAspect {
    private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);
    private static Map<String, DynamicDataSourceNameList> METHOD_DynamicDataSourceNameList_MAP = new HashMap<String, DynamicDataSourceNameList>();

    // 切面 before方法
    public void before(JoinPoint point) {
//        String className = point.getTarget().getClass().getName();
        String method = point.getSignature().getName();
        DynamicDataSourceNameList dynamicDataSourceNameList = METHOD_DynamicDataSourceNameList_MAP.get(method);
        if (dynamicDataSourceNameList != null) {
            DynamicDataSourceHandler.putDataSource(dynamicDataSourceNameList.getDataSourceName());
        } else {
            List<String> dataSourceNameList = new ArrayList<String>();
            DynamicDataSource.METHOD_TYPE_MAP.forEach((dataSourceKey, prefixArray) -> {
                for (String prefix : prefixArray) {
                    if (method.startsWith(prefix)) {
                        dataSourceNameList.add(dataSourceKey);
                        break;
                    }
                }
            });
            if (dataSourceNameList.size() > 0) {
                dynamicDataSourceNameList = new DynamicDataSourceNameList();
                dynamicDataSourceNameList.setDataSourceNameList(dataSourceNameList);
                METHOD_DynamicDataSourceNameList_MAP.put(method, dynamicDataSourceNameList);
                DynamicDataSourceHandler.putDataSource(dynamicDataSourceNameList.getDataSourceName());
            } else {
//                DynamicDataSourceHandler.putDataSource();
            }
        }
        logger.info(method + Base.SPACE + dynamicDataSourceNameList.getDataSourceName());
    }

}
